/*global define, session */
define([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/date/stamp",
    "dojo/date/locale",
    "dojo/dom",
    "dojo/parser", 
    "dojo/ready",
    "dijit/registry",
    "dojo/store/JsonRest",
    "dojo/store/Observable",
    "dgrid/OnDemandGrid",
    "dgrid/Selection",
    "dijit/Toolbar",
    "dojox/form/Manager",
    "dijit/form/TextBox",
    "dijit/form/ValidationTextBox",
    "dijit/form/SimpleTextarea",
    "dijit/form/Button",
    "dijit/form/Select",
    "dijit/Tooltip",
    "dijit/Dialog"
], 
function (declare, lang, timestamp, locale, dom, parser, ready, registry, Rest, Observable, Grid, Selection, Toolbar) {

    return function () {
        var grid, viewForm, editForm, editFormDialog, notempty,
            PlannedGrid, store, currentRecord, rowClick,
            submitData, setDialog, editSchema, viewSchema, newRecord,
            deleteButton, deleteEntry, confirm, filterForm, filterData, 
            formatDate, formatState;
    
        viewSchema = {
            "additional_info": false,
            "new":    true,
            "edit":   false,
            "filter": true,
            "delete": false
        };
        
        editSchema = {
            "additional_info": false,
            "new":    true,
            "edit":   true,
            "filter": true,
            "delete": true
        }; 
        
        newRecord = {
            "additional_info": "",
            "city": "",
            "kfz": "",
            "lb_name": "",
            "state": "" 
        };         
    
        rowClick = function (event) {
        // summary:
        //   Fill the additional_info view and toggle the 
        //   buttons state
        
            currentRecord = grid.row(event).data;
            viewForm.setFormValues(currentRecord);
        
            if (currentRecord.user_id === session.user_id) {
                viewForm.enable(editSchema);
            } else {
                viewForm.enable(viewSchema);
            }
        
        };
            
        submitData = function (event) {

            event.preventDefault();
            event.stopPropagation();

            var values, newRow, isOk;
            
            isOk = editForm.validate();
            
            if (isOk) {
                values = editForm.gatherFormValues();
                newRow = {   
                    additional_info: values.additional_info,
                    city: values.city,
                    kfz: values.kfz.toUpperCase(),
                    lb_name: values.lb_name,
                    state: values.state,
                    user_id: session.user_id,
                    user_name: session.user_name   	    			  
                };
              
                if (editFormDialog.mode === "new") {
                    store.add(newRow);
                } else {
                    newRow = lang.mixin(Object.create(currentRecord), newRow);
                    store.put(newRow);  
                }
                editFormDialog.hide();
            }
            
            return false;
        };  
        
        filterData = function (event) {
            event.preventDefault();
            event.stopPropagation();
            
            var values, key, filter;
            values = filterForm.gatherFormValues();
            filter = {};
            for (key in values) {
                if (values[key]) {
                    filter[key] = values[key];
                }
            }
            grid.set("query", filter);
            viewForm.enable(viewSchema);
            registry.byId("filterDialog").hide();
            viewForm.setFormValues(newRecord);
            return false;
        };
        
        deleteEntry = function () {
            confirm("Wirklich löschen?", 
                "Willst du die diesen Eintrag wirklich löschen?",
                function () {
                    store.remove(currentRecord.id); 
                    viewForm.enable(viewSchema);
                });
        };
        
        setDialog = function () {
            if (this.mode === "new") {
                editForm.setFormValues(newRecord);
            } else {
                editForm.setFormValues(currentRecord);
            }
        };  
        
        confirm = function (title, message, onYes, onNo) {
            
            var p = registry.byId('confirm');           
            onYes = onYes || function () {};
            onNo  = onNo  || function () { 
                p.hide(); 
            };
            
            registry.byId('id_dialog_button_1').attr("style", "color:crimson;font-weight:bold");
            registry.byId('id_dialog_button_1').attr("label", "OK");
 
            p.attr("title", title);
            dom.byId('id_dialog_text').innerHTML = message;
            p.execute = lang.hitch(p, function () {
                if (lang.isObject(arguments)) {
                    onYes();
                } else {
                    onNo();
                }
            });
            p.show();
            
        };        
        
        formatDate = function (item, row) {
            try {
                var d = item.split(" ")[0],
                    t = timestamp.fromISOString(d);
                return locale.format(t, {selector: "date"});
            } catch (e) {
                debugger;
            }
        };
        
        formatState = function (item, row) {
            switch (item) {
            case "1":
                return '<img title="Idee" src="../images/smilies/icon_idea.gif">';
            case "2":
                return '<img title="in Arbeit" src="../images/smilies/icon_exclaim.gif">';
            case "3":
                return '<img title="Fertig!" src="../images/smilies/icon_arrow.gif">';
            }
        };
            
        // create store    
        
        store = new Observable(new Rest({
            target: "/phprestsql/planned_boxes/",
            sortParam: "sort"
        }));        
            
        // create the grid   
        
        PlannedGrid = declare([ Grid, Selection ]);
        grid = new PlannedGrid({
            store: store, 
            columns: [
                {label: "Datum",                    field: "created",    sortable: true, formatter: formatDate},
                {label: "Status",                   field: "state",      sortable: false, formatter: formatState},                    
                {label: "KFZ",                      field: "kfz",        sortable: true},
                {label: "Stadt",                    field: "city",       sortable: true},
                {label: "Kurzbeschreibung/Name",    field: "lb_name",    sortable: false},
                {label: "Nick",                     field: "user_name",  sortable: true}
            ]
        }, "grid");  
        grid.on(".dgrid-row:click", rowClick);
        
        // =========================================================================
        // Connect all GUI elements to the correct handlers
        // =========================================================================
        
        viewForm = registry.byId("viewForm");
        viewForm.enable(viewSchema);
        
        editForm = registry.byId("editForm");
        editForm.on("submit", submitData);
        
        filterForm = registry.byId("filterForm");
        filterForm.on("submit", filterData);
        
        editFormDialog = registry.byId("editBoxDialog");
        editFormDialog.on("show", setDialog);  
        
        deleteButton = registry.byId("delete");
        deleteButton.on("click", deleteEntry);
        
    };
    
});   